package summary

import (
	"varanid-server/models/form/summary"
	"varanid-server/service/token"
	"varanid-server/setting"
	"varanid-server/setting/resp"
	"varanid-server/setting/util"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
	"sync"
)

// GetDailySummary 获取用户访问小程序数据概况【日】
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/data-analysis/analysis.getDailySummary.html
func GetDailySummary(c *gin.Context)  {
	var summaryJson summary.Summary
	if err := c.ShouldBindJSON(&summaryJson); err != nil {
		resp.ParamsError(c)
		return
	}

	url := setting.URL + "/datacube/getweanalysisappiddailysummarytrend?access_token=" + token.AccessToken
	body := make(map[string]interface{})
	body["begin_date"] = summaryJson.BeginDate
	body["end_date"] = summaryJson.EndDate

	resMap, err := util.HttpPostStringMap(&http.Client{}, url, util.MapPostBody(body))
	if err != nil {
		log.Fatalf("GetDailySummary http 错误，url: %s, err: %s", url, err)
	}
	resp.SuccessCustom(c, resMap)
}

var wg sync.WaitGroup
var resMaps = sync.Map{}

// GetWeeklySummary 获取用户访问小程序数据概况【周】，通过goroutine调用7次 GetDailySummarySync 函数
func GetWeeklySummary(c *gin.Context)  {
	var summaryJson summary.Summary
	if err := c.ShouldBindJSON(&summaryJson); err != nil {
		resp.ParamsError(c)
		return
	}

	beginDateNum, err := strconv.Atoi(summaryJson.BeginDate)
	if err != nil {
		log.Fatalf("GetWeeklySummary 字符串转数字错误，err: %s", err)
		resp.Fail(c)
		return
	}

	var dateSlice []string
	beginDateNum--
	for i := 0; i < 7; i++ {
		beginDateNum++
		date := strconv.Itoa(beginDateNum)
		dateSlice = append(dateSlice, date)
	}

	url := setting.URL + "/datacube/getweanalysisappiddailysummarytrend?access_token=" + token.AccessToken

	wg.Add(7)
	for i := 0; i < 7; i++ {
		go GetDailySummarySync(dateSlice[i], url)
	}
	wg.Wait()

	var ret []map[string]interface{}
	for i := 0; i < 7; i++ {
		value, _ := resMaps.Load(dateSlice[i])
		ret = append(ret, value.(map[string]interface{}))
	}

	resp.SuccessCustom(c, ret)
}

// GetDailySummarySync 同步获取用户访问小程序数据概况【日】
func GetDailySummarySync(date string, url string) {
	body := make(map[string]interface{})
	body["begin_date"] = date
	body["end_date"] = date
	resMap, err := util.HttpPostStringMap(&http.Client{}, url, util.MapPostBody(body))
	if err != nil {
		log.Fatalf("GetDailySummarySync http 错误，url: %s, err: %s", url, err)
	}

	m := resMap["list"].([]interface{})[0].(map[string]interface{})
	resMaps.Store(date, m)

	wg.Done()
}
